package com.xaicode.learn.netty.codec;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/13 0013 23:12
 */
@Slf4j
public class NettyServer {

    public static void main(String[] args) {

        // create boss group and worker group
        // boss group deal with accepting
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        // worker group deal with business
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // create server bootstrap
            final ServerBootstrap bootstrap = new ServerBootstrap();
            // bind boss and worker
            bootstrap.group(bossGroup, workerGroup);
            // boss group config
            bootstrap
                    // server use nio socket channel
                    .channel(NioServerSocketChannel.class)
                    // thread queue size
                    .option(ChannelOption.SO_BACKLOG, 128);
            // worker group config
            bootstrap
                    // be active
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    // set worker group`s event pipeline
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        // This method will be called once the Channel was registered.
                        // After the method returns this instance will be removed from the ChannelPipeline of the Channel.
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            // add protobuf decoder to resolve Student
                            pipeline.addLast(new ProtobufDecoder(StudentPOJO.Student.getDefaultInstance()));
                            // add pipeline handler
                            // pipeline.addLast(new NettyServerHandler());
                            pipeline.addLast(new NettyServerHandlerWithSimpleChannel());
                        }
                    });

            // sync bind port and start server
            final ChannelFuture channelFuture = bootstrap.bind(6666).sync();

            // listen closed channel
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // shutdown
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }

    }

}
